import 'package:customer/extension/extension_widget.dart';
import 'package:customer/utils/snackbar.dart';
import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter_gen/gen_l10n/gyy_local.dart';

import '../../../db/entity/AttributeBean.dart';
import '../../../main.dart';
import '../../../widgets/common/empty_data.dart';
import '../../../widgets/gyy_theme.dart';
import '../../../widgets/page.dart';

///编辑属性 - 新增，删除，修改
///tree-view形式
///暂时未启用

class EditAttributeTreePage extends StatefulWidget {
  const EditAttributeTreePage({Key? key}) : super(key: key);

  @override
  State<EditAttributeTreePage> createState() => _EditAttributeState();
}

class _EditAttributeState extends State<EditAttributeTreePage> with PageMixin {
  var attributeDao = database.attributeDao;
  List<AttributeBean> allList = [];
  List<AttributeBean> levelOneList = [];

  TextEditingController attributeNameController = TextEditingController();
  TextEditingController attributeCodeController = TextEditingController();
  AttributeBean selectAttributeBean = AttributeBean(createTime: DateTime.now(), updateTime: DateTime.now());

  //加载所有的
  loadAll() async {
    allList = await attributeDao.findAll();
    levelOneList = allList.where((element) => element.attributeLevel == '1').toList();
    debugPrint(allList.length.toString() + '-----');
    setState(() {});
  }

  //加载二级属性
  Future<List<AttributeBean>> loadChildren(String code) async {
    return attributeDao.findByParentCode(code);
  }

  //新增属性
  addAttribute(String name, String code) {
    // if (selectAttributeBean.attributeCode.isEmpty) {
    //   debugPrint('1--属性：' + name + '  ' + code);
    //   //保存1级属性
    //   attributeDao.insertOne(AttributeBean(
    //       attributeName: name,
    //       attributeCode: code,
    //       attributeValue: '',
    //       attributeLevel: '1',
    //       parentCode: '',
    //       searchType: 0));
    // } else {
    //   debugPrint('2--属性：' + name + '  ' + code);
    //   //保存2级属性
    //   attributeDao.insertOne(AttributeBean(
    //       attributeName: name,
    //       attributeCode: code,
    //       attributeValue: '',
    //       attributeLevel: '2',
    //       parentCode: selectAttributeBean.attributeCode,
    //       searchType: 0));
    // }
  }

  @override
  void initState() {
    super.initState();
    loadAll(); //加载数据
    //初始化文本内容
    // attributeNameController.text = name;
    // attributeNameController.addListener(() {
    //   setState(() {
    //     name = attributeNameController.text;
    //   });
    // });
  }

  @override
  Widget build(BuildContext context) {
    final theme = FluentTheme.of(context);
    return ScaffoldPage.scrollable(
      header: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            GyyLocal.of(context)!.companyName,
            style: theme.typography.title,
          ),
          Text('2022-11-01 01:01:01', style: theme.typography.bodyStrong)
        ],
      ).padding(const EdgeInsets.symmetric(vertical: 0, horizontal: 24)),
      children: [
        sizeBoxV5,
        //操作按钮
        Row(
          children: [
            OutlinedButton(
                child: const Text('查询属性'),
                onPressed: () async {
                  //刷新数据
                  loadAll();
                }),
            sizeBoxH10,
            FilledButton(
                child: Text('新增属性'),
                onPressed: () async {
                  var name = attributeNameController.text;
                  var code = attributeCodeController.text;
                  //添加数据
                  addAttribute(name, code);
                  //刷新数据
                  loadAll();
                }),
            sizeBoxH10,
            Button(
              child: const Text('编辑属性'),
              onPressed: () {
                if (selectAttributeBean.attributeCode.isEmpty) {
                  showMessage(context, "请先选择一个属性");
                } else {

                }
              },
            ),
            sizeBoxH10,
            FilledButton(
                //自定义按钮的颜色
                style: ButtonStyle(
                    backgroundColor: ButtonState.resolveWith(
                  (states) => Colors.errorPrimaryColor,
                )),
                child: Text('删除属性'),
                onPressed: () async {
                  attributeDao.deleteAll();
                }),
          ],
        ),
        sizeBoxV5,
        //输入内容
        Row(
          children: [
            Expanded(
                flex: 5, child: GyyTextInput('属性名称', attributeNameController)),
            sizeBoxH5,
            Expanded(
                flex: 5,
                child: GyyTextInput('属性code：', attributeCodeController))
          ],
        ),
        sizeBoxV5,
        //属性树
        levelOneList.isEmpty
            ? emptyData(const Text('属性数据为空，请维护数据'))
            : Card(
                child: TreeView(
                  selectionMode: TreeViewSelectionMode.single,
                  shrinkWrap: true,
                  items: buildItems(),
                  onSelectionChanged: (selectedItems) async {
                    debugPrint(
                        'onSelectionChanged: ${selectedItems.map((i) => i.itemCode)}');
                    var selectedItem = selectedItems.first;
                    var attributeBean = allList.firstWhere((element) =>
                        element.attributeCode == selectedItem.itemCode);
                    // if (attributeBean == selectAttributeBean) {
                    //   selectAttributeBean = AttributeBean();
                    // } else {
                    //   selectAttributeBean = attributeBean;
                    // }
                    // setState(() {});
                  },
                ),
              ),
      ],
    );
  }

  //构建item
  List<TreeViewItem> buildItems() {
    return levelOneList
        .map((e) => TreeViewItem(
              content: Text(e.attributeName),
      itemCode: e.attributeCode,
              selected: e.attributeCode == selectAttributeBean.attributeCode,
              lazy: true,
              children: [],

              onExpandToggle: (item, getsExpanded) async {
                debugPrint(getsExpanded.toString() + ' ' + selectAttributeBean.attributeCode);
                if (!getsExpanded) return;
                item.children.length = 0;
                await Future.delayed(const Duration(milliseconds: 100));

                var list = await loadChildren(e.attributeCode);
                if(list.isNotEmpty) {
                  debugPrint(list.first.toJson().toString());
                  var newList = list.map((e) => TreeViewItem(
                    content: Text(e.attributeName),
                    itemCode: e.attributeCode,
                    selected: e.attributeCode == selectAttributeBean.attributeCode,
                  )
                  ).toList();
                  // ...and add the fetched nodes.
                  item.children.addAll(newList);
                } else {
                  debugPrint('list.isEmpty');
                }

              },
            ))
        .toList();
  }
}
